<template>
  <el-dialog :title="title" class="editPass" width="350px" :visible.sync="isDial" :before-close='closeDialog'>
    <el-form :model="form" size="mini" :rules='rules' ref="addCity">
      <el-form-item prop='name' label="城市名称" label-width="80px">
        <el-input v-model="form.name" class="leftBorder" autocomplete="off" maxlength="10"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="saveCity">保 存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { request } from "../../assets/request.js";
export default {
    data(){
        return{
            form:{
                name:"",
            },
            title:'添加城市',
            isDial:false,
            rules: {
                name: [
                    {
                        pattern: /\S/,
                        required: true,
                        message: "城市名称不能为空",
                        trigger: "blur"
                    }
                ]
            },
        }
    },
    created(){
        this.$root.$on("addCity",data=>{
            this.isDial=true
            if(data=='add'){
                this.title="添加城市"
            }else{
                let obj={}
                for(let i in data){
                    obj[i]=data[i]
                }
                this.form=obj
                this.title="编辑城市"
                
            }
        })
    },
    methods:{
        saveCity(){
            let that=this
            let form=that.form
            console.log(form)
            this.$refs.addCity.validate(valid => {
                if(!valid){
                    return
                }
                let url='city'
                let met="POST"
                let params={
                    name:form.name,
                    parentId:0
                }
                if(this.title=="编辑城市"){
                    met="PUT"
                    params.id=form.id
                }
                request.ajaxPost({
                    url,
                    that,
                    params,
                    type:met,
                    fn(res) {
                        console.log(res);
                        that.isDial=false
                        that.resetForm();
                        that.$root.$emit('cityList','on')
                    }
                });
            })
        },
        resetForm() { //清空记录
            let form=this.form
            for(let i in form){
                form[i]=""
            }
            this.form=form
            this.$refs['addCity'].resetFields();
        },
        closeDialog(){
            this.isDial=false
            this.resetForm();
        },
    }
};
</script>
<style lang="less" scoped>
.editPass{
    text-align: left;
}
</style>
